#!/bin/bash

if [ -z "${BASH_SOURCE}" ];then
	echo Not in bash, switching to it...
	bash -c "$0 $@"
fi

function choose_fpsoc()
{
	echo "0. non-anlogic chip"
	echo ${ANLOGIC_DEFCONFIG_ARRAY[@]} | xargs -n 1 | sed "=" | sed "N;s/\n/. /"

	local INDEX
	while true; do
		read -p "Which would you like? [0]: " INDEX
		INDEX=$((${INDEX:-0} - 1))

		if [ "$INDEX" -eq -1 ]; then
			echo "Lunching for non-anlogic chip..."
			unset TARGET_OUTPUT_DIR
			unset ANLOGIC_BUILD_CONFIG
			break;
		fi

		if echo $INDEX | grep -vq [^0-9]; then
			ANLOGIC_BUILD_CONFIG="${ANLOGIC_DEFCONFIG_ARRAY[$INDEX]}"
			[ -n "$ANLOGIC_BUILD_CONFIG" ] && break
		fi

		echo
		echo "Choice not available. Please try again."
		echo
	done
}

function setenv()
{
	#export DEVICE_DIR
	export TARGET_DIR_NAME="$ANLOGIC_BUILD_CONFIG"
	#export TARGET_OUTPUT_DIR="$BUILD_OUTPUT_DIR/$TARGET_DIR_NAME"
	#export TARGET_OPENSBI_OUTPUT_DIR="$TARGET_OUTPUT_DIR/opensbi"
	#export TARGET_UBOOT_OUTPUT_DIR="$TARGET_OUTPUT_DIR/u-boot"
	#export TARGET_KERNEL_OUTPUT_DIR="$TARGET_OUTPUT_DIR/linux"
	#export TARGET_BUILDROOT_OUTPUT_DIR="$TARGET_OUTPUT_DIR/buildroot"
	#export TARGET_BOOTSCR_OUTPUT_DIR="$TARGET_OUTPUT_DIR/bootscr"
	#export TARGET_BOOTPART_DIR="$TARGET_OUTPUT_DIR/bootpart"
	#export TARGET_IMG_OUTPUT_DIR="$TARGET_OUTPUT_DIR/image"

	mkdir -p $BUILD_OUTPUT_DIR/$TARGET_DIR_NAME || return
}

function main()
{
	SCRIPT_PATH=$(realpath ${BASH_SOURCE})
	SCRIPT_DIR=$(dirname ${SCRIPT_PATH})

	DEVICE_DIR=${SCRIPT_DIR}/device
	BUILD_OUTPUT_DIR=${DEVICE_DIR}/output
	TOP_DIR=$(dirname ${SCRIPT_PATH})
	echo Top of tree: ${TOP_DIR}

	# Set croot alias
	alias croot="cd ${TOP_DIR}"

	ANLOGIC_DEFCONFIG_ARRAY=(
		$(ls ${DEVICE_DIR}/ | grep "anlogic_" | grep "$1" | sort)
	)

	unset ANLOGIC_BUILD_CONFIG

	ANLOGIC_DEFCONFIG_ARRAY_LEN=${#ANLOGIC_DEFCONFIG_ARRAY[@]}

	case $ANLOGIC_DEFCONFIG_ARRAY_LEN in
		0)
			echo No available configs${1:+" for: $1"}
			;;
		1)
			ANLOGIC_BUILD_CONFIG=${ANLOGIC_DEFCONFIG_ARRAY[0]}
			;;
		*)
			if [ "$1" = ${ANLOGIC_DEFCONFIG_ARRAY[0]} ]; then
				# Prefer exact-match
				ANLOGIC_BUILD_CONFIG=$1
			else
				choose_fpsoc
			fi
			;;
	esac

	[ -n "$ANLOGIC_BUILD_CONFIG" ] || return

	setenv

	#./build.sh lunch
}


if [ "${BASH_SOURCE}" == "$0" ];then
	echo This script is executed directly...
	bash -c "source \"$0\" \"$@\"; bash"
else
	main "$@"
fi
